$.urlParam = function(name){
    let results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
	return results[1] || 0;
};

$(document).ready(function () {
    $('#malaboni').on('click', function (e) {
        let target = $(this);
        target.prop('disabled', true);

        $.ajax({
            url: '/api/v1.1/',
            type: 'POST',
            async: true,
            cache: false,
            dataType: 'json',
            processData: true,
            data: {
                csrfmiddlewaretoken: getCookie('csrftoken'),
                query: 'mutation($email: String!, $token: String!){\n' +
                    '  unsubscribe(email: $email, token: $token){\n' +
                    '    status,\n' +
                    '    message\n' +
                    '  }\n' +
                    '}',
                variables: JSON.stringify({
                    email: decodeURIComponent($.urlParam('poshto')),
                    token: decodeURIComponent($.urlParam('shlosilo'))
                })
            }
        })
            .done(function (response) {
                if(response.data.unsubscribe.status){
                    target.text(response.data.unsubscribe.message)
                        .toggleClass('btn-primary')
                        .toggleClass('btn-secondary');
                }
                else {
                    console.log('Unsubscribe: ' + response.data.unsubscribe.message);
                    target.toggleClass('hidden-element');
                    $('#fail_message').toggleClass('hidden-element');
                }
            })
            .fail(function (jqXHR, textStatus) {
                console.log(textStatus);
                target.prop('disabled', false);
            })
    })
});